package org.example.doctorapi.controller;

import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.example.doctorapi.minio.MinioConfigCommon;
import org.example.doctorapi.minio.MinoUtil;
import org.example.doctorcommon.util.BaseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
@Slf4j
@RestController
@RequestMapping("/minio")
public class MinioController {
    @Autowired
    private MinoUtil minoUtil;
    @Autowired
    private MinioConfigCommon minioConfigCommon;

    @PostMapping("/upload")
    public String uploadCommon(MultipartFile file) {
        //文件名
        String fileName = file.getOriginalFilename();
        String newFileName = System.currentTimeMillis() + "." + StringUtils.substringAfterLast(fileName, ".");
        //类型
        String contentType = file.getContentType();
        minoUtil.uploadFile(minioConfigCommon.getBucketName(), file, newFileName, contentType);
        return "上传成功";
    }

    /**
     * 删除
     *
     * @param fileName
     */
    @DeleteMapping("/delete")
    public void delete(@RequestParam("fileName") String fileName) {
        minoUtil.removeFile(minioConfigCommon.getBucketName(), fileName);
    }
    @GetMapping("/download")
    public BaseResult download(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        try {
            InputStream fileInputStream = minoUtil.getObject(minioConfigCommon.getBucketName(), fileName);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setContentType("application/force-download");
            response.setCharacterEncoding("UTF-8");
            IOUtils.copy(fileInputStream, response.getOutputStream());
            return BaseResult.ok("下载成功");
        } catch (Exception e) {
            log.error("minio文件下载失败:"+e);
            return BaseResult.ok("下载失败");
        }
    }
    @GetMapping("/{fileName}")
    private BaseResult getFile(@PathVariable String fileName) throws IOException {
        InputStream fileInputStream = minoUtil.getObject(minioConfigCommon.getBucketName(), fileName);
        if (fileInputStream.readAllBytes() != null){
            return BaseResult.ok("查询成功");
        }else {
            return BaseResult.ok("查询失败");
        }
    }
}
